package com.valuedaas.schoolsafety.exception;

import com.alibaba.fastjson.JSONException;
import com.mongodb.MongoWriteException;
import com.valuedaas.schoolsafety.common.Constants;
import com.valuedaas.schoolsafety.common.ErrorCodes;
import com.valuedaas.schoolsafety.common.base.Result;
import com.valuedaas.schoolsafety.util.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@ControllerAdvice
public class GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler // 处理所有异常
    @ResponseBody // 在返回自定义相应类的情况下必须有，这是@ControllerAdvice注解的规定
    public String exceptionHandler(Exception ex, HttpServletResponse response) {
        String result = null;
        if (ex instanceof MissingServletRequestParameterException) {
            logger.error(ex.getMessage(), ex);
            MissingServletRequestParameterException mpex = (MissingServletRequestParameterException) ex;
            result = Result.error(ErrorCodes.PARAMETER_MISSING, "缺少参数" + mpex.getParameterName(), null);
        } else if (ex instanceof MissingServletRequestPartException) {
            logger.error(ex.getMessage(), ex);
            MissingServletRequestParameterException mpex = (MissingServletRequestParameterException) ex;
            result = Result.error(ErrorCodes.PARAMETER_MISSING, "缺少参数" + mpex.getParameterName(), null);
        } else if (ex instanceof HttpRequestMethodNotSupportedException) {
            logger.error(ex.getMessage(), ex);
            HttpRequestMethodNotSupportedException mpex = (HttpRequestMethodNotSupportedException) ex;
            result = Result.error(ErrorCodes.PARAMETER_MISSING, "不支持" + mpex.getMethod() + "请求", null);
        } else if (ex instanceof MultipartException) {
            logger.error(ex.getMessage(), ex);
            result = Result.error(ErrorCodes.PARAMETER_MISSING, "缺少上传的图片或文件", null);
        } else if (ex instanceof JSONException) {
            logger.error(ex.getMessage(), ex);
            result = Result.error(ErrorCodes.PARAMETER_ERROR, "Json数据格式错误", null);
        } else if (ex instanceof BizException) {
            logger.error(ex.getMessage(), ex);
            result = Result.error(ErrorCodes.BUSSINESS_ERROR, ex.getMessage(), null);
        } else if (ex instanceof MongoWriteException) {
            if (ex.getMessage().contains("E11000 duplicate key error collection")) {
                logger.error(ex.getMessage(), ex);
                result = Result.error(ErrorCodes.RESOURCE_DUPLICATE, "资源重复", "duplicate key error");
            }
            logger.error(ex.getMessage(), ex);
        } else {
            logger.error("", ex);
            result = Result.error(ErrorCodes.UNKNOW_ERROR, "系统忙，请稍后再试。", ex.getMessage());
        }

        try {
            response.setContentLength(result.getBytes().length); // 注意是字节数
            response.setContentType("application/json;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.print(result);
            pw.flush();
        } catch (Exception e) {
            logger.error("exception handler", e);
        }
        return null;
    }

}
